package com.cloud.prac.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.cloud.prac.config.TemplateHelper;
import com.cloud.prac.model.AssetCacheModel;
import com.cloud.prac.model.AssetCacheModel.AccountAssetListModel;
import com.cloud.prac.model.AssetCacheModel.AccountAssetModel;
import com.cloud.prac.model.AssetCacheModel.FundInfo;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.font.FontProvider;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
@Slf4j
public class FreeMarkerController {

    private final static ConverterProperties properties;

    @Resource
    private Configuration configuration;
    @Resource
    private TemplateHelper templateHelper;

    @GetMapping("/pdf")
    public ResponseEntity<byte[]> pdfTest() throws Exception {
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.set("Accept-Ranges", "bytes");
        final String fileName = "资产证明文件_" + DateTime.now().toString(DatePattern.CHINESE_DATE_TIME_FORMAT) + ".pdf";
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        Template template = configuration.getTemplate("assetInfo.ftlh");
        Map<String, Object> map = new HashMap<>(8);
        map.put("assetInfoModel", getAssetCacheModel());
        templateHelper.put("assetInfo", template.toString());
        String html = templateHelper.toHtmlString("assetInfo", map);
        log.info(html);
        return new ResponseEntity<>(convertToPdf(html), headers, HttpStatus.OK);

    }

    //https://www.cnblogs.com/lin02/p/itext.html
    public static byte[] convertToPdf(String html) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            HtmlConverter.convertToPdf(html, baos, properties);
            return baos.toByteArray();
        } catch (Exception e) {
            log.warn("", e);
        }
        return new byte[0];
    }

    public static void addPdfImgMark() throws Exception {
        String pdfFilePath = "b.pdf";
        String imagePath = "images/stamp.png";
        PdfDocument pdfDocument = new PdfDocument(new PdfReader(pdfFilePath), new PdfWriter(pdfFilePath));
        PdfPage page = pdfDocument.getPage(pdfDocument.getNumberOfPages() - 1);
        Rectangle pageSize = page.getPageSize();

        PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDocument);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);
        Image watermarkImage = new Image(ImageDataFactory.create(imagePath));
        float xPosition = pageSize.getWidth() - watermarkImage.getImageScaledWidth() - 10;
        float yPosition = pageSize.getHeight() - watermarkImage.getImageScaledHeight() - 10;
        canvas.add(watermarkImage.setFixedPosition(xPosition, yPosition));

    }

    static {
        properties = new ConverterProperties();
        try {
            FontProvider fontProvider = new FontProvider();
            PdfFont font = PdfFontFactory.createFont("font/Dengb.ttf");
            fontProvider.addFont(font.getFontProgram());
            properties.setFontProvider(fontProvider);
        } catch (java.io.IOException e) {
            log.warn("", e);
        }
    }

    private static AssetCacheModel getAssetCacheModel() {
        return AssetCacheModel.builder()
                .assetList(
                        CollUtil.toList(
                                AccountAssetListModel.builder().productType("LMF").assetAmountFormat("27393").fundInfoList(getFundList("LMF")).build(),
                                AccountAssetListModel.builder().productType("PMF").assetAmountFormat("87393").fundInfoList(getFundList("PMF")).build()
                        ))
                .assetModel(AccountAssetModel.builder().accountName("aaa").assetAmount("1231").dateFormat(DateUtil.now()).build())
                .build();
    }

    static List<FundInfo> getFundList(String productType) {
        List<FundInfo> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            list.add(FundInfo.builder().fundName(productType + "国寿基金利货币").fundCode("620002").share(i + "13").nav("1.00" + i).navDate("2024-03-25").holdValue("135" + i + "2").build());
        }
        return list;
    }

}
